package com.ys.controller.api.storage;

import com.ys.config.MenuId;
import com.ys.entity.storage.TccOnlinePurchaseReturn;
import com.ys.entity.storage.TccOnlinePurchaseReturnItem;
import com.ys.entity.sys.YsCol;
import com.ys.service.flow.YspTaskService;
import com.ys.service.storage.TccOnlinePurchaseReturnService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @Author: fxz
 * @CreateTime: 2024-11-20
 * @Description: 线上采购退货单控制层
 * @Version: 1.0
 */
@Controller
@RequestMapping("/api/inter/tccOnlinePurchaseReturn")
public class ApiInterTccOnlinePurchaseReturnController {

    private static final Logger logger = Logger.getLogger(ApiInterTccOfflineAssembleController.class);

    @Autowired
    private TccOnlinePurchaseReturnService tccOnlinePurchaseReturnService;

    @Autowired
    private CommonApiService<TccOnlinePurchaseReturn> commonApiService;

    Long MENUID = MenuId.TCC_OnlinePurchaseReturn;
    Long MENUID1 = MenuId.TCC_OnlinePurchaseReturnCkqd;

    @Autowired
    private YspTaskService yspTaskService;


    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccOnlinePurchaseReturn setSeachSql(TccOnlinePurchaseReturn cond,String conditions){

        cond
                .addLeftJoin("TCG_PurchaseByOrder AA ON A.purchaseOrderId = AA.id")
                .addField("FORMAT(AA.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS createTimeByOrder")//创建时间
                .addField("AA.bid AS purchaseOrderBid")//采购完成单号
                .addField("AA.SpBm AS spBm")//商品编码
                .addField("AA.AliOrderNumber AS aliOrderNumber")//1688订单编号
                .addField("AA.Vgsbm AS vgsbm")//运营公司编码
                .addLeftJoin("TCG_PurchaseByPlan H ON H.Bid = AA.PlanBid")//采购计划表
                .addField("H.bid AS purchasePlanBid")//采购计划单号
                .addLeftJoin("THR_OperateCompanyApply E ON E.Vgsbm = AA.Vgsbm ")//运营公司管理表
                .addField("E.Vgsjc AS vgsjc")//采购公司简称
                .addField("E.Vgsmc AS vgsmc")//采购公司名称
                .addLeftJoin("TCG_PurchaseOrderPay AAP ON AAP.purchaseOrderBid = AA.bid")
                .addField("AAP.bid AS purchaseOrderPayBid")//采购付款单号
                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("CASE WHEN P.UpdateTime IS NULL AND A.EffectStock = 1 THEN FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') ELSE FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') END auditingTime")//审核时间

                .addLeftJoin("TCC_OnlinePurchaseReturnItem TOPR ON TOPR.pid = A.id ")
                .addField("TOPR.SubStorageNum AS subStorageNum")//子件库存数量
                .addField("TOPR.subRefundNum AS subRefundNum")//子件退货数量
                .addField("TOPR.subRefundPrice AS subRefundPrice")//子件退货单价
                .addLeftJoin("TCG_PurchaseByOrderSon AAS ON AAS.id = TOPR.purchaseOrderSonId")
                .addField("AAS.subCode AS subCode")//子件编码
                .addField("AAS.sku")//SKU属性
                .addField("AAS.goodsId")//1688商品采购ID
                .addField("AAS.skuId")//SKUID
                .addField("AAS.specId")//SPECID
                .addField("AAS.realityPrice")//子件实际单价
                .addField("AAS.subRealityPrice")//子件采购单价
                .addLeftJoin("TP_ProductBasis G ON G.Code = AA.SpBm ")//商品母件信息表
                .addField("G.Name AS spName")//商品名称
                .addLeftJoin("TCG_PurchaseByPlanSon J ON J.Id = AAS.PurchasePlanSonId ")//计划单子件信息表
                .addField("J.SubName AS subName")//子件商品名称
                .addField("J.SubAmount AS subAmount")//子件BOM数量
                .addField("J.PurchaseAmount AS purchaseAmount")//子件采购数量=母件采购数量*子件数量
                .addField("J.JgSl AS jgSl")//子件加购数量
                .addField("J.SubTotalAmount AS subTotalAmount")//子件采购总数

                .addLeftJoin("TS_UserChange D ON D.id = A.CreateChangeId AND D.Status = 1")
                .addField("D.UserId createUserId")
                .addField("D.UserName createUserName")
                .addField("CASE WHEN A.refundPayType = 0 THEN '支付宝' ELSE 'g跨境宝' END refundPayTypeName")
                .setOrderby("A.Bid DESC");//排序


        return  cond;
    }

    @RequiresPermissions("tccOnlinePurchaseReturn:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TccOnlinePurchaseReturn cond, String conditions){
        cond.setStatus(1);//数据过滤
        cond = setSeachSql(cond,conditions);

        //权限
        cond = commonApiService.dataAuth(MENUID, cond);
        LayuiTableVoJA vo = commonApiService.searchLay(cond);
        return vo;
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccOnlinePurchaseReturn cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond,conditions);
            //权限
            cond = commonApiService.dataAuth(MENUID, cond);

            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MENUID)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TccOnlinePurchaseReturnItem> util = new ExportExcelUtils<>(new TccOnlinePurchaseReturnItem());
            String toFilePath = util.exportExcel(listData, listField, "线上采购退货单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 新增
     */
    @RequiresPermissions("tccOnlinePurchaseReturn:add")
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData
    ) {
        try {
            //新增
            return tccOnlinePurchaseReturnService.add(params,subData);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 删除
     */
    @PostMapping("/deleteTrue")
    @ResponseBody
    public R deleteTrue(HttpServletRequest request, Long id){
        try {
            return tccOnlinePurchaseReturnService.deleteTrue(id);
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions("tccOnlinePurchaseReturn:add")
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData
    ) {
        try {
            //修改
            return tccOnlinePurchaseReturnService.edit(params,subData);
        } catch (Exception e) {
            logger.error("修改出错：", e.getMessage(), e);
            return R.error(e.getMessage());
        }
    }

    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tccOnlinePurchaseReturnService.flowPass(id, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }

    /**
     * 流转退回
     */
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){
        TccOnlinePurchaseReturn entity = new TccOnlinePurchaseReturn().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return yspTaskService.flowRefuse(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("退回出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 流转驳回
     */
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        TccOnlinePurchaseReturn entity = new TccOnlinePurchaseReturn().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return yspTaskService.flowInit(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("驳回出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/exportZj")
    @ResponseBody
    public R exportZj(@ModelAttribute TccOnlinePurchaseReturn cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond.addLeftJoin("TCC_StockFrozenRunning B ON B.SourceBid = A.bid AND B.Status = 1 AND B.NumChange >0")
                .addLeftJoin("TCC_StockControl SC ON SC.Id = B.StockControlId")//库存信息表
                .addField("SC.PurchasePrice AS purchasePrice")//采购单价
                .addField("SC.ProductCode AS productCode")//商品名称
                .addField("SC.ProductName AS productName")//商品编码
                .addLeftJoin("TP_ProductActiveComponent TPA ON TPA.Code = SC.ProductCode")
                .addField("TPA.SubCodeMerge AS codeMerge")//商品合并编码
                .addField("B.NumChange AS numChange")//数量

                .addLeftJoin("TCC_Location SD ON SD.Chw = SC.Chw")//货位信息表
                .addField("SD.Vhw AS subVhw")//货位
                .addLeftJoin("TCC_WarehouseArea SE ON SE.Ckq = SD.Ckq")//库区
                .addField("SE.Vkq AS subVkq")//库区
                .addLeftJoin("TCC_Warehouse SF ON SF.Cck = SE.Cck")//仓库
                .addField("SF.Vck AS subVck")//仓库
                .addLeftJoin("THR_OperateCompanyApply TCA ON TCA.Vgsbm = SC.Vgsbm")//公司信息
                .addField("TCA.Vgsbm AS vgsbm")//运营公司编码
                .addField("TCA.vgsjc AS vgsjc")//运营公司简称
                .addLeftJoin("TB_CompanyInfo TCI ON TCI.VId = SC.CompanyVid")//公司信息
                .addField("TCI.Vname AS vname")//所属公司
                .addField("A.bid AS bid")//备注
            ;
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MENUID1)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TccOnlinePurchaseReturnItem> util = new ExportExcelUtils<>(new TccOnlinePurchaseReturnItem());
            String toFilePath = util.exportExcel(listData, listField, "出库清单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 弹出框（线上组装报错调用）
     */
    @RequestMapping("/searchForModalByOnlineError")
    @ResponseBody
    public LayuiTableVoJA searchForModalByOnlineError(Model model, HttpServletRequest request, HttpServletResponse response,
                                                      @ModelAttribute TccOnlinePurchaseReturn cond, String conditions
    ){
        try {
            logger.info("conditions："+conditions);
            cond
                    .addLeftJoin("TCG_PurchaseByOrder AA ON A.purchaseOrderId = AA.id")
                    .addField("FORMAT(AA.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS createTimeByOrder")//创建时间
                    .addField("AA.bid AS purchaseOrderBid")//采购完成单号
                    .addField("AA.SpBm AS spBm")//商品编码
                    .addField("AA.AliOrderNumber AS aliOrderNumber")//1688订单编号
                    .addField("AA.Vgsbm AS vgsbm")//运营公司编码
                    .addLeftJoin("TCG_PurchaseByPlan H ON H.Bid = AA.PlanBid")//采购计划表
                    .addField("H.bid AS purchasePlanBid")//采购计划单号
                    .addLeftJoin("THR_OperateCompanyApply E ON E.Vgsbm = AA.Vgsbm ")//运营公司管理表
                    .addField("E.Vgsjc AS vgsjc")//采购公司简称
                    .addField("E.Vgsmc AS vgsmc")//采购公司名称
                    .addLeftJoin("TCG_PurchaseOrderPay AAP ON AAP.purchaseOrderBid = AA.bid")
                    .addField("AAP.bid AS purchaseOrderPayBid")//采购付款单号
                    .addLeftJoin("TP_ProductBasis G ON G.Code = AA.SpBm ")//商品母件信息表
                    .addField("G.Name AS spName")//商品名称

                    .addField("A.RefundAmount AS _ys_returnAmount")//退款金额
                    //排序
                    .setOrderby("A.Bid DESC");

            //已被调用过的不调用
            cond.where("(SELECT count(1) FROM TCC_OnlinePurchaseReturnUsed UU WHERE UU.PurchaseReturnBid = A.Bid) = 0 ");

            //已生效
            cond.setEffectStock(1);

            //权限
            cond = commonApiService.dataAuth(MENUID, cond);

            //***锁查询条件
            {
                //锁：退货金额≤该采购订单子件缺失金额
                String returnAmount = ConditionUtil.getConditionValue(conditions, "_ys_returnAmount");//返还金额
                if (returnAmount != null) {
                    cond.where("A.RefundAmount <=" + returnAmount);
                }

            }


            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }



}
